#!/bin/bash

function notify-send()
{
    # Detect the user using such display
    local user=$(who | awk '{print $1}' | head -n 1)

    # Detect the id of the user
    local uid=$(id -u $user)

    sudo -u $user DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus notify-send "$@"
}

function zenity()
{
    # Detect the user using such display
    local user=$(who | awk '{print $1}' | head -n 1)

    # Detect the id of the user
    local uid=$(id -u $user)

    sudo -u $user DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus zenity "$@"
}

confirm_installation() {
    local package_name=$(dpkg-deb -f "$1" Package)
    zenity --question --width=300 --height=250 --text="您正准备安装 ${package_name}\n\n若这次安装请求是您发起的，请按确定继续安装，否则请取消"
    return $?
}

if [ -e /usr/local/bin/ssaudit ]; then

    for DEBPATH in "$@"; do
        DEBPATH="${DEBPATH#file://}"
        DEBPATH=$(realpath "$DEBPATH")

        # 弹出确认窗口
        if confirm_installation "$DEBPATH"; then
            notify-send "正在使用 ssaudit 安装 $(dpkg-deb -f "$DEBPATH" Package)，请稍候...." -i /usr/share/icons/uos-packaging-tools.png
            /usr/local/bin/ssaudit "$DEBPATH" | zenity --text-info --width=500 --height=500 --title="安装输出" --auto-scroll
        else
            notify-send "$(dpkg-deb -f "$DEBPATH" Package) 的安装已取消" -i /usr/share/icons/uos-packaging-tools.png
        fi
        echo "---------------------------------------------------------------------------"
    done
else

    for DEBPATH in "$@"; do
        if [[ $DEBPATH == file://* ]]; then
            DEBPATH="${DEBPATH#file://}"
        fi
        DEBPATH=$(realpath "$DEBPATH")

        # 弹出确认窗口
        if confirm_installation "$DEBPATH"; then
            notify-send "正在使用 apt 安装 $(dpkg-deb -f "$DEBPATH" Package)，请稍候...." -i /usr/share/icons/uos-packaging-tools.png
            apt install "$DEBPATH" --reinstall -y | zenity --text-info --width=500 --height=500 --title="安装输出" --auto-scroll
            if [ "$?" = "0" ]; then
                notify-send "$(dpkg-deb -f "$DEBPATH" Package) 安装已完成" -i /usr/share/icons/uos-packaging-tools.png
            else
                notify-send "$(dpkg-deb -f "$DEBPATH" Package) 安装出错！请手动安装！" -i /usr/share/icons/uos-packaging-tools.png
            fi
        else
            notify-send "$(dpkg-deb -f "$DEBPATH" Package) 的安装已取消" -i /usr/share/icons/uos-packaging-tools.png
        fi
        echo "---------------------------------------------------------------------------"
    done
fi

